require 'digest/sha1'

# Represents contact information. A contact may be associated with zero or more
# members. 
class Contact < ActiveRecord::Base
  has_and_belongs_to_many :members, :join_table => 'member_contacts'
  has_many :sent_emails
  
  validates_presence_of   :email
  
  validates_uniqueness_of :email, :message => "must be unique"
  validate :valid_email?
    
  before_create :create_auth_token
  
protected

  # from http://lindsaar.net/2008/4/14/tip-4-detecting-a-valid-email-address
  def valid_email?
    address = TMail::Address.parse(email)
    
    # also check that we have a domain name with at least one . in it
    raise unless address.domain =~ /\./
  rescue
    errors.add(:email, "[#{email}] is not valid")
  end

  # Creates a random authorization token for this record. The contact can
  # be used, for example, to automatically unsubscribe the contact from
  # receiving emails. We create the token by taking the current time,
  # munging it by sorting the characters randomly, and then getting the
  # SHA1 hash.
  def create_auth_token
    self.auth_token = Digest::SHA1.hexdigest(
        Time.now.to_s.split(//).sort_by {rand}.join)
  end
end
